<?php

class CountAdminController extends Controller {
    /**
     * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
     * using two-column layout. See 'protected/views/layouts/column2.php'.
     */
    public $layout = '//layouts/column2';

    /**
     * @return array action filters
     */
    public function filters() {
        return array(
            'accessControl', // perform access control for CRUD operations
            'postOnly + delete', // we only allow deletion via POST request
        );
    }

    /**
     * Specifies the access control rules.
     * This method is used by the 'accessControl' filter.
     * @return array access control rules
     */
    public function accessRules() {
        return array(
            array(
                'allow', // allow all users to perform 'index' and 'view' actions
                'actions' => array('count'),
                'users' => array('*'),
            ),
            array(
                'allow', // allow authenticated user to perform 'create' and 'update' actions
                'actions' => array('company', 'companyCountDay', 'companyCountYear', 'json_company', 'ajaxGateway'),
                'users' => array('@'),
            ),
            array(
                'allow', // allow admin user to perform 'admin' and 'delete' actions
                'actions' => array('admin', 'countDay', 'countYear', 'update', 'json_admin', 'countpage'),
                'users' => array('admin'),
            ),
            array(
                'deny', // deny all users
                'users' => array('*'),
            ),
        );
    }

    /**
     * Displays a particular model.
     * @param integer $id the ID of the model to be displayed
     */
    public function actionView($id) {
        $this->render('view', array(
            'model' => $this->loadModel($id),
        ));
    }

    /**
     * 超级管理员获取日历json
     */
 
    public function actionJson_admin(){
        $model=CountAdmin::model()->findAll('isMonth=:isMonth',array(':isMonth'=>0));
        $array=array();
        foreach($model as $k=>$v){
            $array[] = array('title'=>'登录数:'.$v['connection_to_day'],'start'=>date('Y-m-d', strtotime($v['createtime'])));
            $array[] = array('title'=>'用户数:'.$v['user_to_day'],'start'=>date('Y-m-d', strtotime($v['createtime'])));
            $array[] = array('title'=>'新增用户:'.$v['user_to_new'],'start'=>date('Y-m-d', strtotime($v['createtime'])));
            $array[] = array('title'=>'路人数:'.$v['guests'],'start'=>date('Y-m-d', strtotime($v['createtime'])));
        }
        echo json_encode($array);
        exit;
    }

    /**
     * 超级管理员按天显示（日历）
     */
 
    public function actionAdmin()
    {
        $dataProvider=new CActiveDataProvider('CountAdmin');
        $count = CountAdmin::model()->find(' isMonth=1 order by createtime desc');
        //统计在线路由数
        $time = date("Y-m-d H:i:s",strtotime(" -6 minute"));
        $lasttimeCount  = Gateway::model()->count(' lasttime >="'.$time.'"');
        $this->render('admin',array(
            'dataProvider'=>$dataProvider,
            'count_users'=>empty($count)?'0':$count->users,
            'count_connections'=>empty($count)?'0':$count->connections,
            'count_gateways'=>empty($count)?'0':$count->gateways,
            'count_companys'=>empty($count)?'0':$count->companys,
            'lasttimeCount'=>$lasttimeCount,
        ));
    }

    /**
     * 超级管理员按天显示
     */
 
	public function actionCountDay()
	{
        $model=CountAdmin::model()->findAll(' isMonth=0 order by createtime desc limit 20');
        foreach ($model as $value) {
            $x[] = date('m-d', strtotime($value->createtime));
            $y[] = array('guests'=>intval($value->guests),'user_to_day'=>intval($value->user_to_day),'user_to_new'=>intval($value->user_to_new),'connection_to_day'=>intval($value->connection_to_day));
        }
        $count = CountAdmin::model()->find(' isMonth=1 order by createtime desc');
        //统计在线路由数
        $time = date("Y-m-d H:i:s",strtotime(" -5 minute"));
        $lasttimeCount  = Gateway::model()->count(' lasttime >="'.$time.'"');
        $this->render('countDay',array(
            'model'=>$model,
            'count_users'=>empty($count)?'0':$count->users,
            'count_connections'=>empty($count)?'0':$count->connections,
            'count_gateways'=>empty($count)?'0':$count->gateways,
            'count_companys'=>empty($count)?'0':$count->companys,
            'lasttimeCount'=>$lasttimeCount,
            'x'=>array_reverse($x),
            'y'=>array_reverse($y), 
        ));
    }

    /**
     * 超级管理员按月显示
     */
    public function actionCountYear() {
        //取得1年的结果
 
        $year = date("Y-m",strtotime("-1 year"));
        $where = ' isMonth=1 ORDER BY createtime DESC limit 12';
        $model=CountAdmin::model()->findAll($where);
        $data = array();
        foreach ($model as $value) {
            $key = date('Y-m', strtotime($value->createtime));
            $data[$key] = array('id'=>$value->id,'guests'=>intval($value->guests),'user_to_day'=>intval($value->user_to_day),'companys'=>intval($value->companys),'gateways'=>intval($value->gateways),'connection_to_day'=>intval($value->connection_to_day)); 
        }
        foreach ($data as $key => $value) {
            $x[] = $key;
            $y[] = $value;
        }
 
        //统计总人数，总登陆数，总企业数，总路由数
        $company= CountAdmin::model()->find(' isMonth=1 order by createtime desc');
        //统计在线路由数
        $time = date("Y-m-d H:i:s",strtotime(" -5 minute"));
        $lasttimeCount  = Gateway::model()->count(' lasttime >="'.$time.'"');
        $this->render('countYear',array(
            'model'=>$model,
            'count_users'=>empty($company)?'0' :$company->users,
            'count_connections'=>empty($company)?'0' :$company->connections,
            'count_gateways'=>empty($company)?'0' :$company->gateways,
            'count_companys'=>empty($company)?'0' :$company->companys,
            'lasttimeCount'=>$lasttimeCount,
            'x'=>array_reverse($x),
            'y'=>array_reverse($y), 
        ));
    }

    /**
     * 企业管理员按天显示（日历）
     */
 
	public function actionCompany()
	{
        $company=CountCompany::model()->find(' isMonth=1 and companyid='.Yii::app()->User->id.' ORDER BY createtime desc');
		$this->render('company',array(
            'count_users'=>empty($company)?'0' :$company->users,
            'count_connections'=>empty($company)?'0' :$company->connections
		));
	}
    /**
     * 企业管理员获取日历json
     */
    public function actionJson_company(){
        if(empty($_GET['id'])) return;
        $model = CountCompany::model()->findAll(' isMonth=0 and companyid='.$_GET['id']);
        $array=array();
        foreach($model as $v){
            $array[] = array('title'=>'登录数:'.$v['connection_to_day'],'start'=>date('Y-m-d', strtotime($v['createtime'])));
            $array[] = array('title'=>'用户数:'.$v['user_to_day'],'start'=>date('Y-m-d', strtotime($v['createtime'])));
            $array[] = array('title'=>'新增用户:'.$v['user_to_new'],'start'=>date('Y-m-d', strtotime($v['createtime'])));
            $array[] = array('title'=>'路人数:'.$v['guests'],'start'=>date('Y-m-d', strtotime($v['createtime'])));
        }
        echo json_encode($array);
        exit;
    }

    /**
     * 企业管理员按天显示
     */
 
    public function actionCompanyCountDay()
    {
        $selected = empty($_GET['gatewayid'])? array() : array($_GET['gatewayid']);
        if(empty($selected)){
            $countcompany=CountCompany::model()->findAll(' isMonth=0 and companyid='.Yii::app()->User->id.' ORDER BY createtime desc  limit 20');
        }else{
            $countcompany=CountGateway::model()->findAll(' isMonth=0 and companyid='.Yii::app()->User->id.' and gatewayid='.$_GET['gatewayid'].' ORDER BY createtime DESC limit 20'); 
        }
        $x = array();
        $y = array();
        if (!empty($countcompany)) {
            foreach ($countcompany as $value) {
                $x[] = date('m-d', strtotime($value->createtime));
                $y[] = array('guests'=>intval($value->guests), 'user_to_day' => intval($value->user_to_day), 'user_to_new' => intval($value->user_to_new), 'connection_to_day' => intval($value->connection_to_day));
            }
        }

        $model = new Gateway();
        //获得总访问数，总用户数
 
        $company=CountCompany::model()->find(' isMonth=1 and companyid='.Yii::app()->User->id.' ORDER BY createtime desc');
        $this->render('companyCountDay',array( 
            'model'=>$model,
            'selected'=>$selected,
            'count_users'=>empty($company)?'0' :$company->users,
            'count_connections'=>empty($company)?'0' :$company->connections,
            'x'=>array_reverse($x),
            'y'=>array_reverse($y), 
        ));
    }

    /**
     * 企业管理员按月显示
     */
    public function actionCompanyCountYear() {
        $selected = empty($_GET['gatewayid']) ? array() : array($_GET['gatewayid']);
        //取得1年的结果
        $year = date("Y-m", strtotime("-1 year"));
        $x = array();
        $y = array();
        $data = array();
        //All 统计
 
        if(empty($selected)){
            $where = '  isMonth=1 and companyid='.Yii::app()->User->id.' ORDER BY createtime DESC limit 12';
            $countcompany=CountCompany::model()->findAll($where);
            foreach ($countcompany as $value) {
                $key = date('Y-m', strtotime($value->createtime));
                    $data[$key] = array('id'=>$value->id,'guests'=>intval($value->guests),'user_to_day'=>intval($value->user_to_day),'user_to_new'=>intval($value->user_to_new),'connection_to_day'=>intval($value->connection_to_day)); 
            }
        }else {
            // 按路由器统计  
            $where = ' isMonth=1 and companyid='.Yii::app()->User->id.' and gatewayid='.$_GET['gatewayid'].' ORDER BY createtime DESC limit 12';
            $countcompany=CountGateway::model()->findAll($where);
            foreach ($countcompany as $value) {
                $key = date('Y-m', strtotime($value->createtime));
                    $data[$key] = array('id'=>$value->id,'guests'=>intval($value->guests),'user_to_day'=>intval($value->users),'connection_to_day'=>intval($value->connections)); 
            }
        }
        foreach ($data as $key => $value) {
            $x[] = $key;
            $y[] = $value;
        }

        //获得总访问数，总用户数
 
        $company=CountCompany::model()->find(' isMonth=1 and companyid='.Yii::app()->User->id.' ORDER BY createtime desc');
        $model=new Gateway(); 
        $this->render('companyCountYear',array(
            'model'=>$model,
            'selected'=>$selected,
            'count_users'=>empty($company)?'0' :$company->users,
            'count_connections'=>empty($company)?'0' :$company->connections,
            'x'=>array_reverse($x),
            'y'=>array_reverse($y), 
        ));
    }


    /**
     * 页面上手动统计
     **/ 
    public function actionCountpage(){ 
         
        $this->render('countpage');
    }
    /**
     * 统计插入到数据库中
     *    默认是统计当天时间的前一天数据。
     *    如果传递要统计的天数，则统计不包含当天的前数据,数据库存在则删除后插入
     * 1、统计超级管理员关注的信息，一天一条
     * 2、统计每一个企业的关注的信息，一天一个企业一条
     * 3、统计每一个路由器关注的信息，一天一个路由一条 
     **/
    public function actionCount() {
        header('Content-type: text/html;charset=utf-8');

        if (empty($_GET['day'])) {
            
            $start = date("Y-m-d");

            $start = date('Y-m-d', strtotime("$start - 1 day"));  
            //统计路由器
            // $this->totalCountGateway($start, "%Y-%m-%d"); 

            // $this->totalCountGateway(date('Y-m', strtotime($start)) , "%Y-%m"); 
            //统计企业
            $this->totalCountCompany($start, "%Y-%m-%d"); 

            $this->totalCountCompany(date('Y-m', strtotime($start)) , "%Y-%m"); 
            //统计管理员
            $this->totalCountAdmin($start, "%Y-%m-%d"); 

            $this->totalCountAdmin(date('Y-m', strtotime($start)) , "%Y-%m");  
            
            echo '<br>统计昨天数据完成。'; 
        }else{
            $start = $_GET['day'];  

            $end = date('Y-m-d', strtotime(date("Y-m-d")." - 1 day")); 

            $days = ceil((strtotime($end) - strtotime($start))/86400);  

            if ( 0 > $days) {
                echo "统计完成！";
                exit;
            } 
            echo "正在统计数据，请稍等...<br>";

             //统计路由器
            // $this->totalCountGateway($start, "%Y-%m-%d"); 

            // $this->totalCountGateway(date('Y-m', strtotime($start)) , "%Y-%m"); 

            //统计企业
            $this->totalCountCompany($start, "%Y-%m-%d"); 

            $this->totalCountCompany(date('Y-m', strtotime($start)) , "%Y-%m");  
            
            // //统计系统管理员
            $this->totalCountAdmin($start , "%Y-%m-%d");

            $this->totalCountAdmin(date('Y-m', strtotime($start)) , "%Y-%m"); 

            // 跳转下一天的统计
            $start = date('Y-m-d', strtotime("$start + 1 day")); 
            echo "<meta http-equiv='refresh' content='0; url=".$this->createUrl('count',array('day'=>$start))."'>";
        }
        exit;   
    }
    /**
     * 统计路由器关注的信息
     **/
    private function totalCountGateway($counttime , $foramt){
        // $connection = Yii::app()->db;
        // // 统计每一个路由的关注的信息
        // // 企业id,企业名称,路由id,路由名称,本路由用户数,本路由连接数，当天本路由用户数,当天本路由连接数,本路由新增用户数,当天本路由路人数
        // $gatewayAll = Gateway::model()->findAll();
        // foreach ($gatewayAll as $key => $gateway) {
        //     //记录统计的数据
        //     $saveData=array();

        //     //统计路由总人数
        //     $sql="select count(DISTINCT userid) as alluser from ".Connectionlog::model()->tableName()." where gatewayid = ".$gateway->id." and date_format(createtime,'".$foramt."')<='".$counttime."'";

        //     $dateAllUser = $connection->createCommand($sql)->queryAll();

        //     $saveData['alluser']=$dateAllUser[0]['alluser'];

        //     //统计路由总连接数
        //     $sql="select count(id) as allcon from ".Connectionlog::model()->tableName()." where gatewayid = ".$gateway->id." and date_format(createtime,'".$foramt."')<='".$counttime."'";

        //     $dateConnect=$connection->createCommand($sql)->queryAll();

        //     foreach ($dateConnect as $key => $dateconnect) {
        //         $saveData['allconnection']=$dateconnect['allcon'];
        //     } 

        //     //当天连接数
        //     $sql = "select count(id) as countnum from " .Connectionlog::model()->tableName()." where gatewayid = ".$gateway->id." and date_format(createtime,'".$foramt."')='".$counttime."'";

        //     $dateConnect = $connection->createCommand($sql)->queryAll();

        //     foreach ($dateConnect as $key => $dateconnect) {
        //         $saveData['todayconnection'] = $dateconnect;
        //     }

        //     //当天用户数
        //     $sql = "select count(DISTINCT userid) as countuser from ".Connectionlog::model()->tableName()." where gatewayid = ".$gateway->id." and date_format(createtime,'".$foramt."')='" . $counttime . "'";
        //     $dateUsers = $connection->createCommand($sql)->queryAll();
        //     foreach ($dateUsers as $key => $dateUser) {
        //           $saveData['todayuser']=$dateusers['countuser'];
        //     }

        //     // 当天路人数
        //     $sql="select count(id) as guest from ".Connectionlog::model()->tableName()." where gatewayid = ".$gateway->id." and date_format(createtime,'".$foramt."') = '".$counttime."' and mobile = 'guest' ";

        //     $dateUsers= $connection->createCommand($sql)->queryAll();

        //     foreach ($dateUsers as $key => $dateusers) {
        //             $saveData['todayguest']=$dateusers['guest'];
        //     }

        //     //新增用户数 . 根据传入的参数判断是统计月还是日
        //     if (count($counttime) > 7) {
        //         $yesterday = date( str_replace('%',"",$foramt) , strtotime("$counttime - 1 day")); 
        //         // echo $yesterday;
        //     }else{
        //         $yesterday = date( str_replace('%',"",$foramt) , strtotime("$counttime - 1 month")); 
        //         // echo $yesterday; 
        //     }

        //     $yesterdaylog = CountGateway::model()->find("createtime = '".$yesterday."'");

        //     if (!empty($yesterdaylog)) {
        //         $saveData['todaynewuser'] = $saveData['alluser'] - $yesterdaylog->users;
        //     }else{
        //         $saveData['todaynewuser'] = $saveData['alluser'];
        //     }

        //     $company = Company::model()->find('id=:compayid', array(':compayid' => $gateway->companyid));

        //     CountGateway::model()->deleteAll("createtime=:createtime", array(":createtime" => $counttime));

        //     $countGateway = new CountGateway();
        //     $countGateway->createtime = $counttime;
        //     $countGateway->companyid = $company->id;
        //     $countGateway->companyname = $company->title;
        //     $countGateway->gatewayid = $gateway->id;
        //     $countGateway->gatewayname = $gateway->gatewayname;

        //     $countGateway->users = $saveData["alluser"];
        //     $countGateway->connections = $saveData["allconnection"];

        //     $countGateway->user_to_day = $savedata["todayuser"];
        //     $countGateway->connection_to_day = $savedata["todayconnection"];
        //     $countGateway->user_to_new = $savedata["todaynewuser"];
        //     $countGateway->guests = $savedata["todayguest"];
        //     $countGateway->save(); 
        // }
    }
    /**
     * 统计企业关注的信息
     **/ 
    private function totalCountCompany($counttime , $foramt){
         $connection = Yii::app()->db;
        // 统计每一个企业的关注的信息
        // 企业id,企业名称,当天本企业用户数,当天本企业连接数,本企业所有用户数,本企业所有连接数,本企业新增用户数,当天本企业路人数
         $companyAll=Company::model()->findAll(); 
         foreach ($companyAll as $key => $company) { 
            //记录统计的数据
            $saveData=array();
            $isMonth = 0;
            //统计企业总人数
            $sql="select count(id) as alluser from ".CompanyUser::model()->tableName()." where  companyid= ".$company->id." and date_format(createtime,'".$foramt."')<='".$counttime."'";

            $dateAllUser = $connection->createCommand($sql)->queryAll(); 

            foreach ($dateAllUser as $key => $datealluser) {
                 $saveData['alluser']=$datealluser['alluser'];
            }  

            //统计企业总连接数
            $sql="select count(id) as allcon from ".Connectionlog::model()->tableName()." where companyid = ".$company->id." and date_format(createtime,'".$foramt."')<='".$counttime."'";

            $dateConnect=$connection->createCommand($sql)->queryAll();

            foreach ($dateConnect as $key => $dateconnect) {
                $saveData['allconnection']=$dateconnect['allcon'];
            } 

            //当天的连接数
            $sql="select count(id) as countAllNum from ".Connectionlog::model()->tableName()." where companyid = ".$company->id." and date_format(createtime,'".$foramt."')='".$counttime."'";

            $dateConnect=$connection->createCommand($sql)->queryAll();

            foreach ($dateConnect as $key => $dateconnect) {
                $saveData['todayconnection']=$dateconnect['countAllNum'];
            }

            //当天的用户数 
            $sql="select count(id) as countuser from ".CompanyUser::model()->tableName()." where companyid = ".$company->id." and date_format(lasttime,'".$foramt."') = '".$counttime."'";

            $dateUsers= $connection->createCommand($sql)->queryAll();

            foreach ($dateUsers as $key => $dateusers) {
                    $saveData['todayuser']=$dateusers['countuser'];
            }

             // 当天路人数
            $sql="select count(id) as guest from ".Connectionlog::model()->tableName()." where companyid = ".$company->id." and date_format(createtime,'".$foramt."') = '".$counttime."' and mobile = 'guest' ";

            $dateUsers= $connection->createCommand($sql)->queryAll();

            foreach ($dateUsers as $key => $dateusers) {
                    $saveData['todayguest']=$dateusers['guest'];
            }

            //新增用户数 . 根据传入的参数判断是统计月还是日 
            if (strlen($counttime) > 7) {
                $yesterday = date( str_replace('%',"",$foramt) , strtotime("$counttime - 1 day"));  
                // echo $yesterday;
            }else{
                $yesterday = date( str_replace('%',"",$foramt) , strtotime("$counttime - 1 month")); 
                $isMonth = 1;
                // echo $yesterday; 
            }

            $yesterdaylog = CountCompany::model()->find("createtime = '".$yesterday."' and  companyid = ".$company->id."");

            if (!empty($yesterdaylog)) {
                $saveData['todaynewuser'] = $saveData['alluser'] - $yesterdaylog->users;
            }else{
                $saveData['todaynewuser'] = $saveData['alluser'];
            }

            //保存数据, 并删除统计当天的那条数据
            CountCompany::model()->deleteAll("createtime=:createtime and companyid=:companyid",array(":createtime"=>$counttime,':companyid'=>$company->id));
            
            $countCompany = new CountCompany();
            $countCompany->createtime = $counttime;

            $countCompany->companyid = $company->id;
            $countCompany->companyname = $company->title;
 
            $countCompany->users = $saveData["alluser"];
            $countCompany->connections = $saveData["allconnection"];

            $countCompany->guests = $saveData['todayguest'];
            $countCompany->user_to_day = $saveData["todayuser"];
            $countCompany->connection_to_day = $saveData["todayconnection"];
            $countCompany->user_to_new = $saveData["todaynewuser"];

            $countCompany->isMonth = $isMonth;

            $countCompany->save(); 
         } 
         echo "企业统计完成，".$counttime."<br>";
    }
     /**
     * 统计管理员关注的信息
     **/ 
    private function totalCountAdmin($counttime , $foramt){
        $connection = Yii::app()->db;
        //记录统计的数据
        $saveData=array();
        $isMonth = 0;
        // 统计管理员的所关注的信息
        // 总企业数
        // $saveData['allcompany'] = Company::model()->count(); 
        $sql="select count(DISTINCT companyid) as countAllcompany from ".Connectionlog::model()->tableName()." where date_format(createtime,'".$foramt."') <= '".$counttime."'";

        $dateCompany= $connection->createCommand($sql)->queryAll();

        foreach ($dateCompany as $datecompany) {
              $saveData['allcompany'] = $datecompany['countAllcompany'];
        }  

        //总路由器数
        // $saveData['allgateway'] = Gateway::model()->count();
         $sql="select count(DISTINCT gatewayid) as countAllgteway from ".Connectionlog::model()->tableName()." where date_format(createtime,'".$foramt."') <= '".$counttime."'";

        $dateGteway= $connection->createCommand($sql)->queryAll();

        foreach ($dateGteway as $dategteway) {
              $saveData['allgateway'] = $dategteway['countAllgteway'];
        }  

        //总连接数
        //$saveData['allconnection'] = Connectionlog::model()->count();
        $sql="select count(id) as allcon from ".Connectionlog::model()->tableName()." where date_format(createtime,'".$foramt."')<='".$counttime."'";

        $dateConnect=$connection->createCommand($sql)->queryAll();

        foreach ($dateConnect as $key => $dateconnect) {
            $saveData['allconnection']=$dateconnect['allcon'];
        } 
 
         //总用户数
        $sql="select count(DISTINCT userid) as countAlluser from ".Connectionlog::model()->tableName()." where date_format(createtime,'".$foramt."') <= '".$counttime."'";

        $dateNewUsers= $connection->createCommand($sql)->queryAll();

        foreach ($dateNewUsers as $datenewusers) {
              $saveData['alluser'] = $datenewusers['countAlluser'];
        }  

        //当天连接数 
        $sql="select count(id) as countnum from ".Connectionlog::model()->tableName()." where  date_format(createtime,'".$foramt."') = '".$counttime."'";
 
        $dateConnect = $connection->createCommand($sql)->queryAll(); 

        foreach ($dateConnect as $dateconnect) {
              $saveData['todayconnection']= $dateconnect['countnum'];
        }

        //得到当天用户数
        $sql="select count(DISTINCT userid) as countuser from ".Connectionlog::model()->tableName()." where date_format(createtime,'".$foramt."') = '".$counttime."'";

        $dateUsers= $connection->createCommand($sql)->queryAll();

        foreach ($dateUsers as $key => $dateusers) {
                $saveData['todayuser']=$dateusers['countuser'];
        }
        // 当天路人数
        $sql="select count(id) as guest from ".Connectionlog::model()->tableName()." where  date_format(createtime,'".$foramt."') = '".$counttime."' and mobile = 'guest' ";

        $dateUsers= $connection->createCommand($sql)->queryAll();

        foreach ($dateUsers as $key => $dateusers) {
                $saveData['todayguest']=$dateusers['guest'];
        }

        //新增用户数 . 根据传入的参数判断是统计月还是日 
        if (strlen($counttime) > 7) {
            $yesterday = date( str_replace('%',"",$foramt) , strtotime("$counttime - 1 day"));  
            // echo $yesterday;
        }else{
            $yesterday = date( str_replace('%',"",$foramt) , strtotime("$counttime - 1 month")); 
            $isMonth = 1;
            // echo $yesterday;

        }
        //得到当天用户数
        $yesterdaylog = CountAdmin::model()->find("createtime = '".$yesterday."'");
        if (!empty($yesterdaylog)) {
            $saveData['todaynewuser'] = $saveData['alluser'] - $yesterdaylog->users;
        }else{
            $saveData['todaynewuser'] = $saveData['alluser'];
        }

        // 保存数据库
        CountAdmin::model()->deleteAll("createtime=:createtime",array(":createtime"=>$counttime));

        $countAdmin = new CountAdmin();

        $countAdmin->createtime = $counttime; 
        $countAdmin->companys = $saveData["allcompany"];
        $countAdmin->gateways = $saveData["allgateway"];
        $countAdmin->users = $saveData["alluser"];
        $countAdmin->connections = $saveData["allconnection"];

        $countAdmin->user_to_day = $saveData["todayuser"];
        $countAdmin->connection_to_day = $saveData["todayconnection"];
        $countAdmin->user_to_new = $saveData['todaynewuser'];
        $countAdmin->guests = $saveData['todayguest'];

        $countAdmin->isMonth = $isMonth; 

        $countAdmin->save();

        echo "管理员统计完成，".$counttime."<br>";
    } 

    /**
     * Returns the data model based on the primary key given in the GET variable.
     * If the data model is not found, an HTTP exception will be raised.
     * @param integer $id the ID of the model to be loaded
     * @return CountAdmin the loaded model
     * @throws CHttpException
     */
    public function loadModel($id) {
        $model = CountAdmin::model()->findByPk($id);
        if ($model === null)
            throw new CHttpException(404, 'The requested page does not exist.');
        return $model;
    }

    /**
     * Performs the AJAX validation.
     * @param CountAdmin $model the model to be validated
     */
    protected function performAjaxValidation($model) {
        if (isset($_POST['ajax']) && $_POST['ajax'] === 'count-admin-form') {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
    }
}
